package com.net.oil.util;

import android.content.Context;
import android.os.Environment;

/**
 * 文件路径工具类，获取系统对应的文件保存路径
 */
public class FilePathUtil {

    private final String dirRoot = "/oilApp";
    private final String dirDownload = "/download";

    private static FilePathUtil instance;

    public static FilePathUtil getInstance() {
        if (instance == null) {
            instance = new FilePathUtil();
        }
        return instance;
    }

    private FilePathUtil() {
    }

    /**
     * 获取下载文件保存路径
     *
     * @param context   context
     * @return  下载路径
     */
    public String getDirDownload(Context context) {
        return getDirRoot(context) + dirDownload;
    }

    /**
     * 获取app在sd卡上的根目录
     *
     * @param context context
     * @return app在sd卡上的根目录
     */
    private String getDirRoot(Context context) {
        return getRootFilePath(context) + dirRoot;
    }

    /**
     * 系统文件根路径
     *
     * @param context context
     * @return 根路径
     */
    private String getRootFilePath(Context context) {
        String rootPath = "";
        if (isHasSdCard()) {
            rootPath = Environment.getExternalStorageDirectory().getAbsolutePath();
        } else if (context.getExternalFilesDir(null) != null) {
            rootPath = context.getExternalFilesDir(null).getAbsolutePath();
        } else if (context.getExternalCacheDir() != null) {
            rootPath = context.getExternalCacheDir().getAbsolutePath();
        } else if (context.getFilesDir() != null) {
            rootPath = context.getFilesDir().getAbsolutePath();
        }
        return rootPath;
    }

    /**
     * 判断sd卡是否存在
     *
     * @return true 存在， false 不存在
     */
    private static boolean isHasSdCard() {
        String sdCardStatus = Environment.getExternalStorageState();
        return sdCardStatus.equals(Environment.MEDIA_MOUNTED);
    }
}
